import { PureComponent, ReactNode } from "react";
import { connect } from "react-redux";
import { View, Button } from "@tarojs/components";
import type { RootState, DispatchType } from "@/store/index";
import { addNumber, subNumber } from "@/store/feature/counter";
import { getHomeData } from "@/store/feature/home";

interface IProps {
  counter: number;
  homeData: any;
  addNumber: (number: number) => void;
  subNumber: (number: number) => void;
  getHomeData: () => void;
}

class ReduxTaro extends PureComponent<IProps> {
  state = {};

  addNumberHandle() {
    this.props.addNumber(1);
  }

  subNumberHandle() {
    this.props.subNumber(1);
  }

  getHomeDataHandle() {
    this.props.getHomeData();
  }

  render(): ReactNode {
    const { counter, homeData } = this.props; // 获取state
    return (
      <View>
        <View>{counter}</View>
        <View>{JSON.stringify(homeData)}</View>
        <Button onClick={() => this.addNumberHandle()}>counter+1</Button>
        <Button onClick={() => this.subNumberHandle()}>counter-1</Button>
        <Button onClick={() => this.getHomeDataHandle()}>getHomeData</Button>
      </View>
    );
  }
}

const mapStateToProps = (state: RootState) => ({
  counter: state.counter.counter,
  homeData: state.home.homeData,
});

const mapDispatchToProps = (dispatch: DispatchType) => ({
  addNumber: (number: number) => dispatch(addNumber(number)),
  subNumber: (number: number) => dispatch(subNumber(number)),
  getHomeData: () => dispatch(getHomeData()),
});

export default connect(mapStateToProps, mapDispatchToProps)(ReduxTaro);
